package com.bruce.tool.pay.alipay.sign;

import com.alipay.easysdk.factory.Factory;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Bruce(刘正航)
 */
@Slf4j
public class AliPaySignUtil {

    /**
     * 回调请求,验签
     * 新版sdk地址
     * https://opendocs.alipay.com/open/00y8k9
     */
    public static boolean verifyNotify(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = Maps.newHashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean isSuccess = false;
        try {
            isSuccess = Factory.Payment.Common().verifyNotify(params);
        } catch (Exception e) {
            log.error("回调结果验签失败", e);
        }
        return isSuccess;
    }
}
